package com.creditease.tmsp.modules.sys.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.creditease.tmsp.common.config.Global;
import com.creditease.tmsp.common.persistence.IdGenerator;
import com.creditease.tmsp.common.web.BaseController;
import com.creditease.tmsp.modules.sys.entity.SysUser;
import com.creditease.tmsp.modules.sys.entity.SysUserRole;
import com.creditease.tmsp.modules.sys.service.RoleService;
import com.creditease.tmsp.modules.sys.service.UserRoleService;
import com.creditease.tmsp.modules.sys.service.UserService;
import com.github.miemiedev.mybatis.paginator.domain.PageList;


/**
 * @Description：用户Controller
 * @author：
 * @CreateDate：
 * @Company:
 * @version V1.0
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/sysuser")
public class SysUserController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	
	@ModelAttribute
	public SysUser get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			SysUser user = userService.getById(id);
	        Map<String, Object> params = new HashMap();
	        params.put("userId", id);
		    List<SysUserRole> roleList =userRoleService.find(params);
		    List<String> roleIdList = new ArrayList();
		    for(SysUserRole sysUserRole : roleList){
		    	roleIdList.add(sysUserRole.getRoleId());
		    }
		    user.setRoleIdList(roleIdList);
			return user;
		}else{
			return new SysUser();
		}
	}
	

	@RequestMapping(value = {"list", ""})
	public String list(SysUser user, HttpServletRequest request, HttpServletResponse response, Model model) {

        List<SysUser> list = userService.query(requestPageBounds(request), convertBeanToMap(user));
        model.addAttribute("user",user);
        model.addAttribute("page", (PageList<SysUser>)list);
		return "modules/sys/userList";
	}

	@RequestMapping(value = "form")
	public String form(SysUser user, Model model) {		
		model.addAttribute("user", user);
		model.addAttribute("allRoles", roleService.find(null));
		return "modules/sys/userForm";
	}

	@RequestMapping(value = "save")
	public String save(SysUser user, String oldLoginName, String newPassword, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		if (!"true".equals(checkLoginName(oldLoginName, user.getLoginName()))){
			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
			return form(user, model);
		}
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(newPassword)) {
			user.setPwd(UserService.entryptPassword(newPassword));
		}
		// 保存用户信息
        try {
			saveOrUpdate(userService, user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//用户角色操作
		String userId = user.getId();
		//删除原用户角色
		userRoleService.deleteByUserIdRoleId(userId, null);
		//保存用户角色
		//不采用批量插入,baseDao有bug
		List<String> roleIdList = user.getRoleIdList();
		SysUserRole userRole = new SysUserRole();
		for(String roleId:roleIdList){
			userRole.setRoleId(roleId);
			userRole.setUserId(userId);
			userRole.setId(IdGenerator.getId());
			userRoleService.save(userRole);
		}

		addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/sys/sysuser/?repage";
	}
	
	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
        if (SysUser.isAdmin(id)){
			addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
		}else{
			userService.delete(id);
			addMessage(redirectAttributes, "删除用户成功");
		}
		return "redirect:"+Global.getAdminPath()+"/sys/sysuser/?repage";
	}

	@ResponseBody
	@RequestMapping(value = "checkLoginName/ajax")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName !=null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName !=null && userService.getByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}

	@RequestMapping(value = "info")
	public String info(SysUser user, Model model) {
		SysUser currentUser = getCrrentUser();
		if (StringUtils.isNotBlank(user.getNickName())){
			currentUser.setEmail(user.getEmail());
			currentUser.setNickName(user.getNickName());
			userService.update(currentUser);
			model.addAttribute("message", "保存用户信息成功");
		}
		model.addAttribute("user", currentUser);
		return "modules/sys/userInfo";
	}


	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		SysUser user = getCrrentUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
			if (userService.validatePassword(oldPassword, user.getPwd())){
				user.setPwd(UserService.entryptPassword(newPassword));
				userService.update(user);
				model.addAttribute("message", "修改密码成功");
			}else{
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}
    
}
